package net.wexoo.onlinedivelog.dal.dive;

import java.util.ArrayList;

import javax.persistence.Query;

import net.wexoo.onlinedivelog.dal.AbstractDAO;
import net.wexoo.onlinedivelog.entity.dive.DiveBean;

import org.apache.wicket.extensions.markup.html.repeater.util.SortParam;
import org.springframework.stereotype.Service;

@Service
public class DiveDAO extends AbstractDAO<DiveBean> implements IDiveDAO {

  public DiveDAO() {
    clazz = DiveBean.class;
  }

  @Override
  public DiveBean getBeanById(int id) {
    DiveBean bean = super.getBeanById(id);
    bean.getDivers();
    return bean;
  }

  @Override
  public ArrayList<DiveBean> getByPerson(int id) {
    return getByPerson(id, null, 0, 0);
  }

  @SuppressWarnings("unchecked")
  @Override
  public ArrayList<DiveBean> getByPerson(int id, SortParam sortParam, int first, int count) {

    StringBuilder queryBuilder = new StringBuilder("select dives from ");
    queryBuilder.append(getBeanClassName());
    queryBuilder.append(" where id = :id");

    if (sortParam != null) {
      queryBuilder.append(" order by p.");
      queryBuilder.append(sortParam.getProperty());
      queryBuilder.append(" ");
      queryBuilder.append(sortParam.isAscending() ? "asc" : "desc");
    }

    Query q = em.createQuery(queryBuilder.toString());

    q.setParameter("id", id);

    if (first != 0)
      q.setFirstResult(first);
    if (count != 0)
      q.setMaxResults(count);

    return (ArrayList<DiveBean>) q.getResultList();
  }

  @Override
  public int getCountByPerson(int id) {
    return getByPerson(id).size();
  }
}